<!--
 * @Author: your name
 * @Date: 2020-08-15 10:24:25
 * @LastEditTime: 2020-08-15 11:20:01
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \cartoon\components\ImgAspect.vue
-->
<template>
  <div class="img-aspect" :style="{paddingBottom:`${(height / width).toFixed(2) * 100}%`, borderRadius: radius + 'px'}">
    <img ref="lazyImg" :style="{borderRadius: radius + 'px'}" :src="lazy ? defaultImage : src">
  </div>
</template>

<script>
import defaultImage from '../static/images/mascot-dance.gif'

export default {
  name: 'ImgAspect',
  props: {
    width: {
      required: true,
      type: Number,
      default: 1
    },
    height: {
      required: true,
      type: Number,
      default: 1
    },
    src: {
      required: true,
      type: String,
      default: ''
    },
    radius: {
      required: true,
      type: Number,
      default: 0
    },
    lazy: {
      required: false,
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      defaultImage
    }
  },
  mounted () {
    if (this.lazy) {
      this.scrollImg()
      window.addEventListener('scroll', this.scrollImg)
    }
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.scrollImg)
  },
  methods: {
    scrollImg () {
      const windowHeight = this.clientXY()
      const el = this.$refs.lazyImg //   const offsetTop = el.offsetTop
      const offsetTop = el.getBoundingClientRect().top
      // console.log('elelelelel', el.getBoundingClientRect().top)
      // console.log('查看ofsetTop', el.offsetTop)
      // console.log('查看ofsetTop', el.offsetTop)
      // console.log('windowHeight', windowHeight)
      if (offsetTop < windowHeight.height + 150) {
        el.src = this.src
      }
    },
    clientXY () {
      if (window.innerHeight !== undefined) {
        return {
          width: window.innerWidth,
          height: window.innerHeight
        }
      } else if (document.compatMode === 'CSS1Compat') {
        return {
          width: document.documentElement.clientWidth,
          height: document.documentElement.clientHeight
        }
      } else {
        return {
          width: document.body.clientWidth,
          height: document.body.clientHeight
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
    .img-aspect {
        width: 100%;
        position: relative;
        img {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0px;
            left: 0px;
        }
    }
</style>
